package com.ac.scum.log.task.face.log.counsumer.stages;

import com.ac.common.core.id.SnowflakeIdGenerator;
import com.ac.scum.log.bean.Player;
import com.ac.scum.log.bean.ServerFTPLogVehicle;
import com.ac.scum.log.task.face.log.counsumer.LogConsumer;
import com.ac.scum.log.task.mapper.log.ServerFTPLogVehicleMapper;
import com.ac.scum.log.task.utils.map.GameMapZoneUtil;
import com.ac.scum.log.task.utils.queue.FTPQueueItem;
import com.google.common.collect.Lists;
import io.micrometer.common.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
@AllArgsConstructor
public class VehicleLogConsumer implements LogConsumer {
    private final GameMapZoneUtil gameMapZoneUtil;
    private final SnowflakeIdGenerator snowflakeIdGenerator;
    private final ServerFTPLogVehicleMapper serverFTPLogVehicleMapper;

    @Override
    public void consumerLog(FTPQueueItem ftpQueueItem) {
        try {
            writeAllPlayerInfoInCache(ftpQueueItem);
            Pattern pattern = Pattern.compile("(\\d{4}\\.\\d{2}\\.\\d{2}-\\d{2}\\.\\d{2}\\.\\d{2}): \\[(\\w+)] (\\w+_ES)\\. VehicleId: (\\d+)\\. Owner: (N/A|\\d+)(?: \\(([^,]+), ([^\\)]+)\\))?\\. Location: X=([\\-\\d\\.]+) Y=([\\-\\d\\.]+) Z=([\\-\\d\\.]+)");

            List<ServerFTPLogVehicle> serverFTPLogChestOwnerships = Lists.newArrayList();
            for (GameLogLine line : splitLine(ftpQueueItem)) {
                String lineContext = line.getLineContext();
                Matcher matcher = pattern.matcher(lineContext);
                ServerFTPLogVehicle serverFTPLogVehicle = new ServerFTPLogVehicle();
                serverFTPLogVehicle.setId(snowflakeIdGenerator.nextId());
                serverFTPLogVehicle.setServerId(ftpQueueItem.getServer().getId());
                serverFTPLogVehicle.setFileId(ftpQueueItem.getFileId());
                serverFTPLogVehicle.setLineStart(line.getStartByte());
                serverFTPLogVehicle.setLineEnd(line.getEndByte());
                serverFTPLogVehicle.setCreateTime(LocalDateTime.now());
                if (matcher.matches()) {
                    String timestamp = matcher.group(1);
                    String eventType = matcher.group(2).trim().toLowerCase();
                    String vehicle = matcher.group(3).trim().toLowerCase();
                    Long vehicleId = Long.parseLong(matcher.group(4));
                    Long playerSteamId = matcher.group(5).equals("N/A") ? null : Long.parseLong(matcher.group(5));
                    String playerName = matcher.group(7) != null ? matcher.group(7) : Strings.EMPTY;
                    String x = matcher.group(8);
                    String y = matcher.group(9);
                    String z = matcher.group(10);

                    if (StringUtils.isNotBlank(playerName)) {
                        Player player = getOrInsertPlayerServer(playerSteamId, serverFTPLogVehicle.getServerId(), playerName);
                        serverFTPLogVehicle.setOwnerPlayerId(player.getId());
                        serverFTPLogVehicle.setOwnerPlayerSteamId(player.getSteamId());
                    }
                    serverFTPLogVehicle.setVehicleId(vehicleId);
                    String spawnItemCodeCnName = getSpawnItemCodeCnName(vehicle);
                    serverFTPLogVehicle.setVehicleName(spawnItemCodeCnName);
                    serverFTPLogVehicle.setType(getVehicleType(eventType));
                    serverFTPLogVehicle.setServerTime(parseTimestamp(timestamp, ftpQueueItem));
                    serverFTPLogVehicle.setLocation(String.format("%s %s %s", x, y, z));
                    serverFTPLogVehicle.setLocationZone(gameMapZoneUtil.getZone(Double.parseDouble(x), Double.parseDouble(y)));
                } else {
                    commitDiscardLog(ftpQueueItem, line, "vehicle");
                }
                serverFTPLogChestOwnerships.add(serverFTPLogVehicle);
            }
            serverFTPLogChestOwnerships.forEach(serverFTPLogVehicleMapper::insert);
        } catch (Exception e) {
            log.error("载具日志出现异常", e);
        }
    }

    private Integer getVehicleType(String type) {
        //1摧毁 2消失
        return switch (type) {
            case "destroyed" -> 1;
            case "disappeared" -> 2;
            default -> 9;
        };
    }
}
